using System.Text;
using KL.Standard.Domain.Repositories;
using KL.Standard.Model.Infrastructure;
using KL.Standard.Model.Models.BaseArch;
using KL.Standard.Model.ViewModels.OutResult;
using KL.Standard.Repositories.MutliDataSource;

using Dapper;
using KL.Standard.Core.Extensions;
using KL.Standard.Core.Utils;
using KL.Standard.Model.Attribute;
using KL.Standard.Model.Contant;

namespace KL.Standard.Repositories.BaseArch;

public class UserRepository:BaseRepository<SysAccountPO,ECPDataSource>, IUserRepository
{
    private string tenantId  = typeof(ECPDataSource).Name.Replace("DataSource", "");
    public int RestPwd(string[] loginIdArray)
    {
        var paramList = loginIdArray.Select(i => new
        {
            loginID = i,
            pwd = MD5Util.md5("123456", 32)
        });
        string vSql = @"update sys_account set password = @pwd where loginID= @loginID;";
        return this.DbConn.Execute(vSql, paramList);
    }

    public int Delete(string[] loginIdArray)
    {
        var paramList = loginIdArray.Select(i => new
        {
            loginID = i
        });
        string vSql = @"update sys_account set isDelete = 1 where loginID= @loginID and isSystem = 0";
        return this.DbConn.Execute(vSql, paramList);
    }

    public int Lock(string loginId)
    {
        string vSql =
                "update sys_account set isLock = (case when isLock = 1 then  0 else 1 end) where loginID=@loginID and isSystem = 0 ;";
        return this.DbConn.Execute(vSql, new { loginId });
    }
    [RepoUseTran("ECP")]
    public int UpdateLoginInfo(SysAccountPO po)
    {
        var dbTran = this.DbTransaction(tenantId);
        string vSql = @"
    INSERT INTO [dbo].[sys_operation_log]
           ([userID]
           ,[loginID]
           ,[module]
           ,[opeType]
           )
     VALUES
           (@userID 
           ,@loginID 
           ,@module 
           ,@opeType); ";
        string vSql2 = @"update sys_account set loginCount=isnull(loginCount,0)+1,loginLastIP=@loginLastIP where id = @userID";
        var newid = Guid.NewGuid().ToString();
        int flag = this.DbConn.Execute(vSql, new { userID = po.id, loginID = po.loginID, module = "登录", opeType = OperationType.LOGIN }, dbTran);
        flag += this.DbConn.Execute(vSql2, new { loginLastIP = "", userID = po.id }, dbTran);
        //transaction.Commit();
        return flag;
    }

    public AccountVM QueryUserInfo(string pLoginId)
    {
        string vSql = string.Format(@"
                SELECT * FROM dbo.v_account_info
                    WHERE isDelete = 0
                    AND loginID= @loginID;
             ");
        return this.DbConn.QueryFirstOrDefault<AccountVM>(vSql, new { loginID = pLoginId });
    }

    public async Task<PageResult<AccountVM>> SearchPage(PageSearchModel para)
    {
        var vSql = new StringBuilder(" select * from v_account_info where isDelete= 0 ");
            DynamicParameters dp = new DynamicParameters();
            if (para.searchParam.ContainsKey("loginID"))
            {
                vSql.Append($" and loginID LIKE '%'+@loginID+'%' ");
                dp.Add("loginID", para.searchParam["loginID"]);
            }
            if (para.searchParam.ContainsKey("nickName"))
            {
                vSql.Append($" and nickName LIKE '%'+@nickName+'%' ");
                dp.Add("nickName", para.searchParam["nickName"]);
            }
            if (para.searchParam.ContainsKey("email"))
            {
                vSql.Append($" and email LIKE '%'+@email+'%' ");
                dp.Add("email", para.searchParam["email"]);
            }
            if (para.searchParam.ContainsKey("moblie"))
            {
                vSql.Append($" and moblie LIKE '%'+@moblie+'%' ");
                dp.Add("moblie", para.searchParam["moblie"]);
            }
            if (para.searchParam.ContainsKey("roleID"))
            {
                if (para.searchParam["roleID"].ToString() != "0" && para.searchParam["roleID"].ToString() != "")
                {
                    vSql.Append($" and roleID = @roleID ");
                    dp.Add("roleID", para.searchParam["roleID"]);
                }
            }
            if (para.searchParam.ContainsKey("isLock"))
            {
                vSql.Append($" and isLock = @isLock ");
                dp.Add("isLock", para.searchParam["isLock"]);
            }
            if (para.searchParam.ContainsKey("isDelete"))
            {
                vSql.Append($" and isDelete = @isDelete ");
                dp.Add("isDelete", para.searchParam["isDelete"]);
            }
            if (!para.searchParam.IsEmpty("companyID"))
            {
                if (para.searchParam["companyID"] != "0")
                {
                    vSql.Append($" and companyID = @companyID ");
                    dp.Add("companyID", para.searchParam["companyID"]);
                }
            }
            para.Sort = "id";
            para.Order = "desc";
            //System.Console.WriteLine("1111");
            var pager = await this.PagerAsync<AccountVM>(vSql.ToString(), dp, para);
            pager.pageIndex = para.pageIndex;
            pager.pageSize = para.Limit;
            return pager;
    }

    public bool IsExist(SysAccountPO info)
    {
        var vSql = new StringBuilder(" select count(*) from sys_account where loginID = @loginID ");
        if (info.id > 0) //修改
        {
            vSql.Append(" and id <> @id ");
        }
        var count = this.DbConn.QueryFirst<Int32>(vSql.ToString(), info);
        return count > 0;
    }

    [RepoUseTran("ECP")]
    public long SaveInfo(SysAccountPO info)
    {
        var tran = this.DbTransaction(tenantId);
        if (info.id > 0)
        {
            string vSql =
                @" update sys_account set loginID = @loginID,email = @email,mobile = @mobile ,
                        nickName = @nickName,deptID = @deptID,companyID = @companyID,positionID = @positionID,
                        updatedTime = getdate(),remark = @remark where id = @id ;";
            vSql += $@"delete from r_account_role where loginID = @loginID;";
            vSql += $@"insert into r_account_role (loginID,roleID) VALUES (@loginID,@roleID);";
            return this.DbConn.Execute(vSql, info, tran);
        }
        else
        {
            info.password = MD5Util.md5("123456", 32);
            string vSql =
                @"
                    INSERT INTO [dbo].[sys_account]
                           ([loginID]
                           ,[password]
                           ,[nickName]
                           ,[companyID]
                           ,[deptID]
                           ,[positionID]
                           ,[mobile]
                           ,[email]
                           ,[creatorID]
                           ,[createdTime]
                           ,[updatorID]
                           ,[updatedTime]
                           ,[remark]
                           ,[isSystem],isDelete)
                     VALUES
                           (
                           @loginID
                           ,@password
                           ,@nickName
                           ,@companyID
                           ,@deptID
                           ,@positionID
                           ,@mobile
                           ,@email
                           ,@creatorID
                           ,getdate()
                           ,@creatorID
                           ,getdate()
                           ,@remark
                           ,0,0);
                        ";
            vSql += $@"delete from r_account_role where loginID = @loginID;";
            vSql += $@"insert into r_account_role (loginID,roleID) VALUES (@loginID,@roleID);";
            return this.DbConn.Execute(vSql, info, tran);
        }
    }

    [RepoUseTran("ECP")]
    public int SaveInfo4ZT(SysAccountPO info)
    {
        var tran = this.DbTransaction(tenantId);
        int c = this.DbConn.QueryFirstOrDefault<int>("select count(id) from sys_account where loginID=@loginID;",
            info, tran);
        if (c > 0)
        {
            string vSql =
                @" update sys_account set email = @email,mobile = @mobile ,
                        nickName = @nickName,deptID = @deptID,companyID = @companyID,positionID = @positionID,
                        updatedTime = getdate(),remark = @remark  where loginID=@loginID ;";
            vSql += $@"delete from r_account_role where loginID = @loginID;";
            vSql += $@"insert into r_account_role (loginID,roleID) VALUES (@loginID,@roleID);";
            return this.DbConn.Execute(vSql, info, tran);
        }
        else
        {
            info.password = MD5Util.md5("123456", 32);
            string vSql =
                @"
                    INSERT INTO [dbo].[sys_account]
                           ([loginID]
                           ,[password]
                           ,[nickName]
                           ,[companyID]
                           ,[deptID]
                           ,[positionID]
                           ,[mobile]
                           ,[email]
                           ,[creatorID]
                           ,[createdTime]
                           ,[updatorID]
                           ,[updatedTime]
                           ,[remark]
                           ,[isSystem],isDelete)
                     VALUES
                           (@loginID
                           ,@password
                           ,@nickName
                           ,@companyID
                           ,@deptID
                           ,@positionID
                           ,@mobile
                           ,@email
                           ,@creatorID
                           ,getdate()
                           ,@creatorID
                           ,getdate()
                           ,@remark
                           ,0,0);
                        ";
            vSql += $@"delete from r_account_role where loginID = @loginID;";
            vSql += $@"insert into r_account_role (loginID,roleID) VALUES (@loginID,@roleID);";
            return this.DbConn.Execute(vSql, info, tran);
        }
    }

    public int UpdateNewPwd(string loginId, string newPwd)
    {
        string vSql = @"update sys_account set password = @newPwd where loginID= @loginID ;";
        return this.DbConn.Execute(vSql, new { newPwd = newPwd, loginID = loginId });
    }
}